package cn.itcast.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.itcast.domain.dto.ChatDTO;
import cn.itcast.service.ChatService;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

/**
 * @author robin
 * @date 25.7.17 17:33
 */
@Service
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {
    private final ChatClient chatClient;

    @Override
    public String chat(ChatDTO chatDTO) {
        return chatClient.prompt()
                         .system(prompt -> prompt.param("now", DateUtil.now()))
                         .advisors(advisor -> advisor.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatDTO.getSessionId()))
                         .user(chatDTO.getQuestion())
                         .call()
                         .content();
    }

    @Override
    public Flux<String> chatStream(ChatDTO chatDTO) {
        return chatClient.prompt()
                         .system(prompt -> prompt.param("now", DateUtil.now()))
                         .advisors(advisor -> advisor.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatDTO.getSessionId()))
                         .user(chatDTO.getQuestion())
                         .stream()
                         .content()
                         .doOnNext(System.out::println)
                         .concatWith(Flux.just("[END]"));
    }
}
